//
//  MusicDetailViewController.m
//  享动
//
//  Created by darker on 16/4/9.
//  Copyright © 2016年 HHUI. All rights reserved.
//

#import "MusicDetailViewController.h"
#import "MusicDetailTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MusicPlayViewController.h"
#import "musicListModel.h"
#import <MJRefresh.h>
#import <FMDatabase.h>
@interface MusicDetailViewController ()<UITableViewDataSource,UITableViewDelegate>


@property(nonatomic, strong)NSMutableArray * modelArray;
@property(nonatomic, strong)NSMutableArray *iconArray;

@property (weak, nonatomic) IBOutlet UILabel *typeLabel;

@property (weak, nonatomic) IBOutlet UILabel *speed;
@property (weak, nonatomic) IBOutlet UILabel *tempLabel;
@property(nonatomic,assign)NSInteger startIndex;

@property (weak, nonatomic) IBOutlet UIView *bigView;
@property(nonatomic,strong)NSMutableArray * anotherArr;

@property(nonatomic,strong)FMDatabase * db;


@end

@implementation MusicDetailViewController

- (void)getByUrl:(NSString *)url
{

    NSDictionary * dic = @{@"index":@"0"};
    _iconArray = [NSMutableArray array];
    [RequestManager requestWithUrl:url requestType:RequestTypePost parDic:dic finish:^(NSData *data) {
        NSDictionary * allDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * resultArray  = allDic[@"page"][@"result"];
        
        
        for (NSDictionary * one in resultArray) {
            
            musicRunModel * model = [[musicRunModel alloc]init];
            
            [model setValuesForKeysWithDictionary:one];
           // NSLog(@"%@",model.name);
            [_modelArray addObject:model];
//            NSLog(@"%@", model.albumUrl);
            [_iconArray addObject:model.albumUrl];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
           
            
            musicRunModel * model = _modelArray[0];
            [self.iconView sd_setImageWithURL:[NSURL URLWithString:model.albumUrl]];
            self.typeLabel.text = self.typeString;
            self.tempLabel.text = [NSString stringWithFormat:@"节拍:%ld",model.bpm];
            self.speed.text = model.author;
            
             [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
     self.navigationController.navigationBarHidden = YES;
    
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)loadMore
{
    _startIndex += 1;

    _anotherArr = [NSMutableArray array];
    
    
    NSDictionary * dic = @{@"index":[NSString stringWithFormat:@"%ld",_startIndex]};
    
    [RequestManager requestWithUrl:_urlString requestType:RequestTypePost parDic:dic finish:^(NSData *data) {
        NSDictionary * allDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray * resultArray  = allDic[@"page"][@"result"];
        
        
        for (NSDictionary * one in resultArray) {
            musicRunModel * model = [[musicRunModel alloc]init];
            [model setValuesForKeysWithDictionary:one];
            [_anotherArr addObject:model];
            [_iconArray addObject:model.albumUrl];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.modelArray addObjectsFromArray:_anotherArr];
            
            [self.tableView reloadData];
            
        });
        
    } error:^(NSError *error) {
        NSLog(@"错误");
    }];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.frame = CGRectMake(0, 0, KWIDTH, KHEIGHT);
    
      
    self.tableView.delegate = self;
    
    self.tableView.dataSource =self;
    
    [self.tableView registerClass:[MusicDetailTableViewCell class] forCellReuseIdentifier:@"cell"];

    
    _modelArray  = [NSMutableArray array];
    
    // 前面七个就解析  后面的就从数据库取
    if (_index < 7) {
         [self getByUrl:_urlString];
    }
    else
    {
        
        musicListModel * model = _musicListArray[_index-7];
        _iconView.image = [UIImage imageWithData:model.iconViewData];
        _typeLabel.text = model.listName;
        _speed.text = model.introduce;
        
        
        // 取值
        NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"chooseMusic.db"];

        _db = [FMDatabase databaseWithPath:path];
        [_db open];
        FMResultSet * rr = [_db executeQuery:@"SELECT * FROM chooseMusic"];
        
        
        while ([rr next]) {
            
        musicRunModel * model = [[musicRunModel alloc]init];
            
            model.tableName = [rr stringForColumn:@"tableName"];
            model.albumUrl = [rr stringForColumn:@"albumUrl"];
                model.author = [rr stringForColumn:@"author"];
                model.name = [rr stringForColumn:@"name"];
                model.introduce = [rr stringForColumn:@"introduce"];
                model.url = [rr stringForColumn:@"url"];
                model.bpm = [rr intForColumn:@"bpm"];
            
            if ([model.tableName isEqualToString:_tableName]) {
  
                [_modelArray addObject:model];
            }
            
        }
        [rr close];
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
        });
        
    }
    
    
    // 上拉加载
    _tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self loadMore];
        
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    musicRunModel *model = self.modelArray[indexPath.row];
    
    [cell cellFormodel:model];
    cell.selectionStyle  = UITableViewCellSelectionStyleNone;
    

    if (model.isChoose) {
        cell.chooseView.hidden = NO;
    }
    else
    {
        cell.chooseView.hidden = YES;
    }
    
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    for (MusicDetailTableViewCell * cell in self.tableView.visibleCells) {
        cell.chooseView.hidden = YES;
    }
    for (musicRunModel *model in self.modelArray) {
        model.isChoose = NO;
    }
    

    
       MusicPlayViewController * play = [[MusicPlayViewController alloc]initWithNibName:@"musicPlay" bundle:[NSBundle mainBundle]];
       musicRunModel * model = self.modelArray[indexPath.row];
    
       play.model = model;
       
       play.modelArray = _modelArray;
       
       play.index = indexPath.row;
    
    // -------------------------------- 显示谁被选中的歌曲
    model.isChoose = YES;
    
    MusicDetailTableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    cell.chooseView.hidden = NO;
    
    
    
    [self presentViewController:play animated:YES completion:nil];

}










- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(modalViewControllerDidClickedDismissButton:)]) {
        [self.delegate modalViewControllerDidClickedDismissButton:self];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
